import sys
import pygame
import socket
import threading

server_host = '127.0.0.1'  # 服务器的 IP 地址
server_port = 9999  # 服务器使用的端口号
# self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


class Game:
    def __init__(self, surface):
        self.is_ready1 = False
        self.is_ready2 = False
        self.wait = True
        self.start1 = True
        self.iswin = -2
        self.isfailure = False
        self.issend = False
        self.mydapao = 0
        self.myfanghuzhao = 0
        self.myhealth = 5
        self.yourhealth = 5
        self.yourdapao = 0
        self.yourfanghuzhao = 0
        self.surface = surface
        self.clock = pygame.time.Clock()
        self.roomnumber = ''
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.client_socket.connect((server_host, server_port))
            print('Connected to server')
        except socket.error as e:
            print("Socket error occurred:", e)
        self.receive_thread = threading.Thread(target=self.receive_messages)
        self.receive_thread.start()
        self.begin()

    def receive_messages(self):
        while True:
            try:
                # 接收服务器发送的数据
                data = self.client_socket.recv(1024).decode('utf-8')
                # 调用回调函数处理接收到的消息
                if data:
                    self.message_callback(data)
            except socket.error as e:
                # 服务器断开连接
                print("Socket error occurred:", e)
                self.client_socket.close()
                break

    def message_callback(self, data):
        if data == "1 ready":
            self.is_ready1 = True
        elif data == "2 ready":
            self.is_ready2 = True
        elif data == "start":
            self.wait = False
        elif data == 'same':
            self.iswin = 0
            self.issend = False
        elif data == 'win':
            self.iswin = 1
            self.issend = False
        elif data == 'failure':
            self.iswin = 2
            self.issend = False
        elif data == "dapao":
            self.yourdapao += 1
        elif data == "fanghuzhao":
            if self.yourfanghuzhao < 9:
                self.yourfanghuzhao += 3
        elif "attack=" in data:
            attack = int(data[7:])
            print(attack)
            if self.myfanghuzhao < attack:
                attack -= self.myfanghuzhao
                self.myfanghuzhao = 0
                if self.mydapao <= attack:
                    attack -= self.mydapao
                    self.mydapao = 0
                    if self.myhealth <= attack:
                        self.isfailure = True
                        self.start1 = False
                    else:
                        self.myhealth -= attack
                else:
                    self.mydapao -= attack
            else:
                self.myfanghuzhao -= attack

    def begin(self):
        beginimg = pygame.image.load("../img/begin.png")
        startbuttonimg = pygame.image.load("../img/startbutton.png")
        button_width = startbuttonimg.get_width()
        button_height = startbuttonimg.get_height()
        running = True
        buttonsurface = startbuttonimg
        buttonsurface_rect = buttonsurface.get_rect(center=(70, 300))
        while running:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                elif event.type == pygame.MOUSEMOTION:
                    mouse_pos = pygame.mouse.get_pos()
                    if buttonsurface_rect.collidepoint(mouse_pos):
                        buttonsurface = pygame.transform.scale(startbuttonimg, (button_width+10, button_height+10))
                        buttonsurface_rect = buttonsurface.get_rect(center=(70, 300))
                    else:
                        buttonsurface = startbuttonimg
                        buttonsurface_rect = buttonsurface.get_rect(center=(70, 300))
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    if buttonsurface_rect.collidepoint(mouse_pos):
                        running = False

            # 渲染开始页面的代码
            self.surface.blit(beginimg, (0, 0))  # 渲染背景图片
            self.surface.blit(buttonsurface, buttonsurface_rect)  # 渲染按钮图片
            self.clock.tick(60)
            self.update()
        self.ready()

    def ready(self):
        pygame.key.set_repeat(200, 50)  # 设置键盘重复事件
        createroom = pygame.image.load("../img/creatroom.png")
        joinroom = pygame.image.load("../img/joinroom.png")
        createroom_rect = createroom.get_rect()
        joinroom_rect = joinroom.get_rect()
        createroom_rect.center = (300, 300)
        joinroom_rect.center = (300, 450)
        ready = True
        input_box = pygame.Rect(150, 130, 300, 70)
        font = pygame.font.Font(None, 64)
        input_text = 'please input!'
        while ready:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_BACKSPACE:
                        input_text = input_text[:-1]
                    elif input_text == 'please input!':
                        input_text = ''
                    else:
                        input_text += event.unicode
                    self.roomnumber = input_text

                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    if createroom_rect.collidepoint(mouse_pos):
                        self.creatroom()
                        ready = False
                    elif joinroom_rect.collidepoint(mouse_pos):
                        self.joinroom()
                        ready = False
            self.clock.tick(60)
            self.surface.fill((0, 0, 0))
            pygame.draw.rect(self.surface, (255, 255, 255), input_box, 0)
            text_surface = font.render(input_text, True, (0, 0, 0))
            self.surface.blit(text_surface, input_box)
            self.surface.blit(createroom, createroom_rect)
            self.surface.blit(joinroom, joinroom_rect)
            self.update()

    def creatroom(self):
        self.client_socket.sendall(("roomnumber="+self.roomnumber).encode())
        self.is_ready1 = True
        me = pygame.Rect(100, 225, 150, 150)
        he = pygame.Rect(350, 225, 150, 150)
        while self.wait:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if self.is_ready2 and self.is_ready1 and event.key == pygame.K_RETURN:
                        self.client_socket.sendall("start".encode())
                        self.wait = False
            self.surface.fill((255, 255, 255))
            if self.is_ready1:
                pygame.draw.rect(self.surface, (0, 255, 0), me, 0)
            else:
                pygame.draw.rect(self.surface, (255, 0, 0), me, 0)
            if self.is_ready2:
                pygame.draw.rect(self.surface, (0, 255, 0), he, 0)
            else:
                pygame.draw.rect(self.surface, (255, 0, 0), he, 0)
            self.clock.tick(60)
            self.update()
        self.start()

    def joinroom(self):
        self.client_socket.sendall(("joinroom="+self.roomnumber).encode())
        self.is_ready1 = True
        self.is_ready2 = True
        self.wait = True
        me = pygame.Rect(100, 225, 150, 150)
        he = pygame.Rect(350, 225, 150, 150)
        while self.wait:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            self.surface.fill((255, 255, 255))
            # response = self.client_socket.recv(1024).decode()
            if self.is_ready1:
                pygame.draw.rect(self.surface, (0, 255, 0), me, 0)
            else:
                pygame.draw.rect(self.surface, (255, 0, 0), me, 0)
            if self.is_ready2:
                pygame.draw.rect(self.surface, (0, 255, 0), he, 0)
            else:
                pygame.draw.rect(self.surface, (255, 0, 0), he, 0)
            self.clock.tick(60)
            self.update()
        self.start()

    def start(self):
        self.surface = pygame.display.set_mode((1000, 600))
        rock = pygame.image.load("../img/rock.png")
        scissors = pygame.image.load("../img/scissors.png")
        paper = pygame.image.load("../img/paper.png")
        mydapao = pygame.image.load("../img/cannon.png")
        yourdapao = pygame.transform.flip(mydapao, True, True)
        myfanghuzhao = pygame.image.load("../img/protective-cover.png")
        yourfanghuzhao = pygame.transform.flip(myfanghuzhao, True, True)
        startbackground = pygame.image.load("../img/background.png")
        flag1 = pygame.image.load("../img/flag1.png")
        flag2 = pygame.image.load("../img/flag2.png")
        flag2 = pygame.transform.flip(flag2, True, True)
        flag1_rect = flag1.get_rect()
        flag2_rect = flag2.get_rect()
        flag1_rect.x = 250
        flag1_rect.y = 500
        flag2_rect.x = 250
        font_path = "../data/font.ttf"
        font = pygame.font.Font(font_path, 52)
        text = font.render("5 代表布", True, (255, 255, 255))
        text2 = font.render("2 代表剪刀", True, (255, 255, 255))
        text3 = font.render("0 代表石头", True, (255, 255, 255))
        text4 = font.render("选择并按回车", True, (255, 255, 255))
        # text5 = font.render("我的大炮数量", True, (0, 0, 0))
        # text6 = font.render("我的防护罩血量", True, (0, 0, 0))
        # text7 = font.render("我的旗子血量", True, (0, 0, 0))
        # text8 = font.render("你的大炮数量", True, (0, 0, 0))
        # text9 = font.render("你的防护罩血量", True, (0, 0, 0))
        # text10 = font.render("你的旗子血量", True, (0, 0, 0))
        select = '2'
        while self.start1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_5:
                        select = '5'
                    elif event.key == pygame.K_2:
                        select = '2'
                    elif event.key == pygame.K_0:
                        select = '0'
                    elif event.key == pygame.K_RETURN:
                        if not self.issend and self.iswin in [-2, 0, 2]:
                            self.client_socket.send(select.encode())
                            self.issend = True
                            self.iswin = -1
                        text = font.render("a 代表修建大炮", True, (255, 255, 255))
                        text2 = font.render("s 代表修建防护罩", True, (255, 255, 255))
                        text3 = font.render("d 代表进攻", True, (255, 255, 255))
                    elif event.key == pygame.K_a and self.iswin == 1:
                        self.iswin = -2
                        self.mydapao += 1
                        self.client_socket.send("dapao".encode())
                    elif event.key == pygame.K_s and self.iswin == 1:
                        self.iswin = -2
                        if self.myfanghuzhao < 9:
                            self.myfanghuzhao += 3
                            self.client_socket.send("fanghuzhao".encode())
                    elif event.key == pygame.K_d and self.iswin == 1:
                        self.iswin = -2
                        self.client_socket.send("attack={}".format(self.mydapao).encode())
                        attack = self.mydapao
                        if self.yourfanghuzhao < attack:
                            attack -= self.yourfanghuzhao
                            self.yourfanghuzhao = 0
                            if self.yourdapao < attack:
                                attack -= self.yourdapao
                                self.yourdapao = 0
                                if self.yourhealth <= attack:
                                    self.start1 = False
                                    self.isfailure = False
                                else:
                                    self.yourhealth -= attack
                            else:
                                self.yourdapao -= attack
                        else:
                            self.yourfanghuzhao -= attack
            if self.iswin == -2:
                text4 = font.render("等待你出", True, (255, 255, 255))
            elif self.iswin == -1:
                text4 = font.render("等待对方出", True, (255, 255, 255))
            elif self.iswin == 0:
                text4 = font.render("平局了", True, (255, 255, 255))
            elif self.iswin == 1:
                text4 = font.render("你赢啦·-·", True, (255, 255, 255))
            elif self.iswin == 2:
                text4 = font.render("你输啦.-.", True, (255, 255, 255))
            self.surface.fill((0, 0, 0))
            self.surface.blit(startbackground, (0, 0))
            self.surface.blit(flag1, flag1_rect)
            self.surface.blit(flag2, flag2_rect)
            if self.mydapao != 0:
                self.surface.blit(mydapao, (250, 370))
                text5 = font.render("*{}".format(self.mydapao), True, (0, 0, 0))
                self.surface.blit(text5, (360, 400))
            if self.myfanghuzhao != 0:
                self.surface.blit(myfanghuzhao, (100, 310))
                text6 = font.render("*{}".format(self.myfanghuzhao), True, (0, 0, 0))
                self.surface.blit(text6, (110, 320))
            if self.myhealth != 0:
                text7 = font.render("*{}".format(self.myhealth), True, (0, 0, 0))
                self.surface.blit(text7, (220, 520))
            if self.yourdapao != 0:
                self.surface.blit(yourdapao, (250, 130))
                text8 = font.render("*{}".format(self.yourdapao), True, (0, 0, 0))
                self.surface.blit(text8, (360, 150))
            if self.yourfanghuzhao != 0:
                self.surface.blit(yourfanghuzhao, (100, 0))
                text9 = font.render("*{}".format(self.yourfanghuzhao), True, (0, 0, 0))
                self.surface.blit(text9, (110, 200))
            if self.yourhealth != 0:
                text10 = font.render("*{}".format(self.yourhealth), True, (0, 0, 0))
                self.surface.blit(text10, (310, 20))

            self.surface.blit(text, (650, 50))
            self.surface.blit(text2, (650, 100))
            self.surface.blit(text3, (650, 150))
            self.surface.blit(text4, (650, 200))
            if select == '5':
                self.surface.blit(paper, (650, 250))
            elif select == '2':
                self.surface.blit(scissors, (730, 250))
            elif select == '0':
                self.surface.blit(rock, (730, 250))

            self.clock.tick(60)
            self.update()
        if self.isfailure:
            self.failure()
        else:
            self.win()

    def win(self):
        self.surface = pygame.display.set_mode((600, 600))

    def failure(self):
        self.surface = pygame.display.set_mode((600, 600))

    def update(self):
        pygame.display.update()
